package lh.companion.track.server.netty;

import com.alibaba.fastjson.JSON;
import com.corundumstudio.socketio.SocketIONamespace;
import com.corundumstudio.socketio.SocketIOServer;
import com.github.nkzawa.socketio.client.Socket;
import lh.companion.track.server.model.RealTrack;
import lh.companion.track.server.repository.RealTrackRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lh on 2017/12/20.
 */

public class NettyServer {
    Logger logger = LoggerFactory.getLogger(NettyServer.class);

    @Autowired
    private SocketIOServer server;
    private static final String ACTIVITY = "activity";
    private static List<RealTrack> realTracks1 = new ArrayList<>(100);
    private static List<RealTrack> realTracks2 = new ArrayList<>(100);
    private static boolean isRealTrack1 = true;

    @Autowired
    private RealTrackRepository trackRepository;

    @Value("${track.save.max}")
    private int TRACK_SAVE_MAX;

    private void init() {
        start();
        connectMonitor();
    }

    public void createNamespace(Long activityId) {
        SocketIONamespace namespace = server.addNamespace("/" + ACTIVITY + "_" + activityId);
        namespace.addEventListener(Socket.EVENT_MESSAGE, String.class, (client, data, ackRequest) -> {
            namespace.getBroadcastOperations().sendEvent(Socket.EVENT_MESSAGE, data);
            RealTrack track = JSON.parseObject(data, RealTrack.class);
            if (isRealTrack1) {
                realTracks1.add(track);
            } else {
                realTracks2.add(track);
            }
        });
    }

    public void deleteNamespace(Long activityId) {
        server.removeNamespace("/" + ACTIVITY + "_" + activityId);
    }

    @Scheduled(fixedRate = 60 * 1000)
    public void trackToDB() {
        if (isRealTrack1 && realTracks1.size() > 0) {
            isRealTrack1 = false;
            trackRepository.save(realTracks1);
            realTracks1.clear();
            isRealTrack1 = true;
        } else if (isRealTrack1 && realTracks2.size() > 0) {
            trackRepository.save(realTracks2);
            realTracks2.clear();
        }
    }

    private void connectMonitor() {
        server.addConnectListener(client -> {
            logger.info("来自{}的连接，sessionId：{}", client.getRemoteAddress(), client.getSessionId());
        });
    }

    private void start() {
        server.start();
    }
}
